namespace Game.Networking.Server {
	public class NetworkUnitEventsWatcher : UnitEventsWatcher {
		ServerScriptController SC => ServerScriptController.Instance;

		ServerController Server => ServerController.Instance;

		ClientState GetAssociatedClient() {
			if ( _target == null ) {
				return null;
			}
			var playerName = _target.OwnerUser;
			var client = Server.GetClientByName(playerName);
			return client;
		}

		public override void OnAttachedEntityIdChanged(uint newEntity) {
			var client = GetAssociatedClient();
			if ( client == null ) {
				return;
			}
			using ( ByteStreamFormatter formatter = new ByteStreamFormatter() ) {
				formatter.Write_Uint(newEntity);
				Server.SendNetMessage(client, ServerPacketID.InfoUpdateEvent, new S_InfoUpdateMessage() { EventType = InfoEventType.UnitAttachedEntityIdChanged, EventArgs = formatter.GetData() });
			}
		}

		protected override void OnCodeFileUpdated(string fileName) {
			return;
		}

		protected override void OnFileListChanged() {
			var client = GetAssociatedClient();
			if ( client == null ) {
				return;
			}
			Server.SendNetMessage(client, ServerPacketID.ProgramFileListSend, new S_ProgramListMessage() { ProgramList = _target.GetSourceCodeFileNames() });
		}

		protected override void OnUnitStateChanged() {
			var client = GetAssociatedClient();
			if ( client == null ) {
				return;
			}
			using ( ByteStreamFormatter formatter = new ByteStreamFormatter() ) {
				formatter.Write_Byte((byte)_target.State);
				Server.SendNetMessage(client, ServerPacketID.InfoUpdateEvent, new S_InfoUpdateMessage() { EventType = InfoEventType.UnitStateChanged, EventArgs = formatter.GetData() });
			}
		}

		protected override void OnTerminalCommand(TerminalCommandEvent cmd) {
			var client = GetAssociatedClient();
			if ( client == null ) {
				return;
			}
			var comm = new S_ProgramConsoleCommand() { Command = cmd.Command, CommandArgs = cmd.Args };
			Server.SendNetMessage(client, ServerPacketID.ProgramConsoleCommand, comm);
		}
	}
}
